package com.controller;

import com.common.ResultBean;
import com.util.UserInfo;
import com.util.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@RequestMapping
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtils jwtTokenProvider;

    @PostMapping("/login")
    public ResultBean<String> login(@RequestParam("username") String username,
                        @RequestParam("password") String password) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        UserInfo userInfo = createUserInfo(username);
        return ResultBean.ok(jwtTokenProvider.createToken(userInfo));
    }

    private UserInfo createUserInfo(String username) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(new Random().nextLong());
        userInfo.setName(username);
        return userInfo;
    }
}
